import {PlainBindingNamespace, PlainRuleNamespace, RuleEditor} from "@peryl/react-cms-editor";
import {designComponent, onBeforeUnmount, PropType} from "@peryl/react-compose";
import {useRuleEditorOption} from "../../modules/cms-visual-editor";
import {deepcopy} from "@peryl/utils/deepcopy";
import {iRuleRecord, iRuleResultRecord} from "./RuleList";
import {createEffects} from "@peryl/utils/createEffects";

export const RuleListPageEditor = designComponent({
  name: 'rule-list-page-editor',
  props: {
    ruleMetas: { type: Object as PropType<PlainRuleNamespace.iRuleMeta[] | undefined | null> },
    ruleVariables: { type: Object as PropType<PlainBindingNamespace.iBindingVariables | undefined | null> },
    initializeVariablesWithInitialValue: { type: Boolean },
    disable: { type: Boolean },
    showBackButton: { type: Boolean },
  },
  emits: {
    onSave: (data: iRuleRecord['jsonData']) => true,
    onRunFinish: (data: Partial<iRuleResultRecord>) => true,
    onCallBack: () => true,
  },
  setup({ props, event: { emit } }) {

    const { effects: setupEffects } = createEffects();

    const ruleEditorOption = useRuleEditorOption({
      isRunning: false,
      disable: props.disable,
      enableParamVariablesForRuleEditor: true,
      data: {
        ruleMetas: deepcopy(props.ruleMetas || []),
        ruleVariables: deepcopy(props.ruleVariables || {}),
      }
    });

    props.showBackButton && ruleEditorOption.button.left.registry(99, 'back', {
      render: {
        icon: 'pi-arrow-left',
        label: '返回',
        handler: () => {emit.onCallBack();},
        disabled: false,
      }
    });

    setupEffects.push(ruleEditorOption.hooks.onRunFinish.use(data => {
      const newRuleResultRecord: Partial<iRuleResultRecord> = {
        ...data.rootRuleResult,
        meta: data.allRuleResults
      };
      emit.onRunFinish(newRuleResultRecord);
    }));

    setupEffects.push(ruleEditorOption.hooks.onUpdateVariables.use(() => {handler.emitSaveData();}));

    setupEffects.push(ruleEditorOption.hooks.onUpdateData.use(() => {handler.emitSaveData();}));

    ruleEditorOption.editorRuleState.bindingRunningState.checkBindingVariables({ initializeWithInitialValue: props.initializeVariablesWithInitialValue });

    const handler = {
      /*向父组件派发要保存的数据*/
      emitSaveData: () => {
        const saveData: iRuleRecord['jsonData'] = deepcopy({
          ruleMetas: ruleEditorOption.state.getStateData(),
          ruleVariables: ruleEditorOption.editorRuleState.state.ruleVariables
        });
        emit.onSave(saveData);
      },
    };

    onBeforeUnmount(() => {setupEffects.clear();});

    return () => (
      <RuleEditor option={ruleEditorOption}/>
    );
  },
});
